<?php
namespace library;
use library\exceptions\ExceptionNotFound as ExceptionNotFound;
/**
 * zestaw metod do zarządzania tablicami
 *
 * @author Damian Jóźwiak
 */
class ArrayMethods {
    private function __construct() {
     }
     private function __clone() {
     }
     public static function clean($array){
         return array_filter($array, function($item){
             return !empty($item);
         });
     }
        public static function first($array)
        {
            if (sizeof($array) == 0)
            {
                return null;
            }
            
            $keys = array_keys($array);
            return $array[$keys[0]];
        }
        
        public static function last($array)
        {
            if (sizeof($array) == 0)
            {
                return null;
            }
            
            $keys = array_keys($array);
            return $array[$keys[sizeof($keys) - 1]];
        }
     public static function trim($array){
         return array_map(function($item){
             return trim($item);
         }, $array);
     }
     /**
      * funkcja pobiera element z tablicy
      * @param mixed $key -wymagany klucz
      * @param array $array - przeszukiwana tablica
      * @return mixed
      * @throws ExceptionNotFound 
      */
     public static function getElement($key,$array){
         if(!isset($array[$key])) {
             throw new ExceptionNotFound($key);
         }
         return $array[$key];
     }
     public static function toObject($array){
         $result = new \stdClass();
        if (!is_array($array) && !is_object($array)){
            return $array;
        }
         foreach ($array as $key => $value) {
                          
             if (is_array($value)){                 
                 $result->{$key} = self::toObject($value);
             }
             else {
                 $result->{$key}=$value;
             }
         }
         return $result;
     }
     public static function flattern($array, $return = array()){
         foreach ($array as $key => $value) {
             if (is_array($value) || is_object($value)){
                 $return = self::flattern($value,$return);
             }
             else $return[]=$value;
         }
         return $return;
     }
     public static function escape($array, $return = array()){
         $connector = Registry::get("database");
         $connector->connect();
         foreach ($array as $key => $value) {
             if (is_array($value) || is_object($value)){
                 $return = self::escape($value,$return);
             }
             else {
                 $return[]=$connector->escape($value);
             }
         }
         return $return;
     }
}
